package util

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

const port string = "5432"
const dbname string = "postgres"
const user string = "postgres"
const driverName string = "postgres"
const password string = "123456"
const sslmode string = "disable"

var db *sql.DB

//获取*sql.DB
func GetDb() *sql.DB {
	return db
}

//初始化Db
func InitDb() {
	sourceString := "user=" + user + " password=" + password + " dbname=" + dbname + " sslmode=" + sslmode
	db2, err := sql.Open(driverName, sourceString)
	db = db2
	fmt.Println("Init DB Success")
	if err != nil {
		fmt.Println("From:InitDb:---", err.Error())
	}
}

//关闭数据库
func CloseDb(db *sql.DB) {
	err := db.Close()
	if err != nil {
		fmt.Println("From: CloseDb:---", err.Error())
	}
}

func Exec(sql string, args ...interface{}) (sql.Result, error) {

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		return nil, err
	}
	result, err := stmt.Exec(args...)
	if err != nil {
		return nil, err
	}

	return result, nil

}

func Query(sql string, args ...interface{}) (*sql.Rows, error) {

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		return nil, err
	}
	rows, err := stmt.Query(args...)
	if err != nil {
		return nil, err
	}

	return rows, nil

}
